package com.hrt.common.safe;

import com.btcode.common.AbstractSingleton;
import com.btcode.common.PassWordUtil;
import com.btcode.exception.BusinessException;
import com.btcode.orm.model.IModel;
import com.hrt.common.safe.user.UserStatus;
import com.hrt.common.safe.exception.UserDisableException;
import java.util.List;

public class UserSafeService extends AbstractSingleton implements IUserService {

    private static IUserService service;

    @Override
    public IUser getUser(String userid) {

        return service.getUser(userid);
    }

    @Override
    public List<IModel> getUserFunction(String userId) {

        return service.getUserFunction(userId);
    }

    public static void setService(IUserService userService) {
        service = userService;
    }

    @Override
    public IUser getModelByLogin(String account, String password)
        throws AccountNotExistException, PasswordErrorException,UserDisableException {

        if (account == null || password == null) {
            throw new BusinessException("账号或者密码不能为空");
        }

        if(!LoginLock.getCanLogin(account)){
            throw new BusinessException("用户已被锁定(60分钟),请联系管理员");
        }

        IUser user = service.getModelByLogin(account, password);

        if (user == null) {
            throw new AccountNotExistException("账号不存在");
        }

        String md5PassWord = PassWordUtil.encryptPassWordByMd5(account,password);
        if (!md5PassWord.equals(user.getPassword())) {
            throw new PasswordErrorException("密码错误");
        }

        if(user.getStatus().equals(UserStatus.Disable)){
            throw new UserDisableException("用户已停用");
        }

        return user;
    }

}
